﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Net;


namespace QuickWeb
{
    class RSSTextTrimmer : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string fixedString = "";
            if (value == null) return null;
            int maxLength = (int)parameter;
            int strLength = 0;
            fixedString = Regex.Replace(value.ToString(), "<[^>]+>", string.Empty);
            fixedString = fixedString.Replace("\r", "").Replace("\n", "");
            fixedString = HttpUtility.HtmlDecode(fixedString);
            strLength = fixedString.ToString().Length;
            if (strLength == 0)
            {
                return null;
            }
            if(maxLength>0){
                if (strLength >= maxLength)
                {
                   fixedString = fixedString.Substring(0, maxLength);
                   fixedString = fixedString.Substring(0, fixedString.LastIndexOf(" "));
                   fixedString += "...";
                }
            }            
            return fixedString;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }


    }
}
